package edu.ccut.saturn.studio.menuitem.page;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IDetailsPage;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.SectionPart;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import org.w3c.dom.Node;

import edu.ccut.saturn.studio.core.search.SaturnFileSearcher.SearchResult;
import edu.ccut.saturn.studio.core.search.dialog.TowComponentSearchInProjectDialog;
import edu.ccut.saturn.studio.core.search.dialog.TwoCompontentSearchDialog;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.menuitem.model.MenuItem;
import edu.ccut.saturn.studio.menuitem.model.MenuItemModel;

public class MenuItemsDetailsPage implements IDetailsPage {
	private MenuItemsPage page;
	private IManagedForm managedform;
	private MenuItem menuItem;
	private SectionPart secPart;
	private Text labelText;
	private Text pathText;
	private Text orderText;
	private Shell shell;
	private MenuItemModel menuItemModel;
	private IProject project;
//	private static final String SEARCH_ELEMENT_ACTION = "action"; //$NON-NLS-1$
//	private static final String SEARCH_ELEMENT_JSP = "jsp"; //$NON-NLS-1$

	public MenuItemsDetailsPage(MenuItemsPage menupage,
			MenuItemModel menuItemModel, IProject projectd) {

		this.page = menupage;
		this.shell = page.getSite().getShell();
		this.menuItemModel = menuItemModel;
		this.project = projectd;
	}

	public void createContents(Composite composite) {
		TableWrapLayout tablewraplayout = new TableWrapLayout();
		tablewraplayout.topMargin = 0;
		tablewraplayout.leftMargin = 5;
		tablewraplayout.rightMargin = 0;
		tablewraplayout.bottomMargin = 0;
		composite.setLayout(tablewraplayout);
		FormToolkit formtoolkit = managedform.getToolkit();
		createFieldMappingSection(formtoolkit, composite);
	}

	private Text createonlyreadText(FormToolkit formtoolkit, Composite composite) {
		Text text = new Text(composite, SWT.BORDER | SWT.READ_ONLY); //$NON-NLS-1$
		GridData text_data = new GridData(SWT.FILL, SWT.CENTER, true, false);
		text_data.horizontalSpan = 2;
		text.setLayoutData(text_data);
		return text;
	}

	private Text createshortText(FormToolkit formtoolkit, Composite composite) {
		Text text = new Text(composite, SWT.BORDER); //$NON-NLS-1$
		GridData text_data = new GridData(SWT.FILL, SWT.CENTER, true, false);
		text_data.horizontalSpan = 1;
		text.setLayoutData(text_data);
		return text;
	}

	private Button createButton(FormToolkit formtoolkit, Composite composite,
			String text) {
		Button button = formtoolkit.createButton(composite, text, SWT.NONE);
		GridData button_data = new GridData();
		button_data.horizontalSpan = 1;
		button_data.verticalAlignment = SWT.BOTTOM;
		button.setLayoutData(button_data);
		return button;
	}

	private void createFieldMappingSection(FormToolkit formtoolkit,
			Composite composite) {
		Section section = createSection(formtoolkit, composite, Messages
				.getString("MenuItemsDetailsPage.nodeproperty")); //$NON-NLS-1$
		Composite composite1 = formtoolkit.createComposite(section);
		GridLayout gridlayout = new GridLayout();
		gridlayout.marginWidth = gridlayout.marginHeight = 2;
		gridlayout.verticalSpacing = 7;
		gridlayout.horizontalSpacing = 3;
		gridlayout.numColumns = 3;
		composite1.setLayout(gridlayout);

		formtoolkit.createLabel(composite1, Messages
				.getString("MenuItemsDetailsPage.showname")); //$NON-NLS-1$
		labelText = createonlyreadText(formtoolkit, composite1);
		labelText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				menuItem.setLabel(labelText.getText().trim());
				menuItemModel.changeMenuItemAttribute(menuItem.getId(),
						MenuItemModel.MENUITEM_ATTRIBUTE_LABEL, labelText
								.getText()); //$NON-NLS-1$
			}
		});

		formtoolkit.createLabel(composite1, Messages
				.getString("MenuItemsDetailsPage.url")); //$NON-NLS-1$
		pathText = createshortText(formtoolkit, composite1);
		pathText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				menuItem.setPath(pathText.getText().trim());
				menuItemModel.changeMenuItemAttribute(menuItem.getId(),
						MenuItemModel.MENUITEM_ATTRIBUTE_PATH, pathText
								.getText()); //$NON-NLS-1$

			}
		});
		Button button = createButton(formtoolkit, composite1, Messages
				.getString("MenuItemsDetailsPage.browse")); //$NON-NLS-1$
		button.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(final SelectionEvent e) {
//				if (project != null) {
//					List<String> oldAllList = SearchFile.searchInSrc(project,
//							new String[] { SEARCH_ELEMENT_JSP,
//									SEARCH_ELEMENT_ACTION }); //$NON-NLS-1$ //$NON-NLS-2$
//					List<String> allList = formatPath(oldAllList);
//					String[] allArray = (String[]) allList
//							.toArray(new String[allList.size()]);
//
//					String[] jspArray = formatArray(allArray,
//							SEARCH_ELEMENT_JSP); //$NON-NLS-1$
//
//					String[] actionArray = formatArray(allArray,
//							SEARCH_ELEMENT_ACTION); //$NON-NLS-1$
//
//					String[][] res = { allArray, jspArray, actionArray };
//
//					FilterDialog dialog = new FilterDialog(shell,
//							new SaturnSWTUtils.SaturnLabelDefaultProvider() {
//								public String getText(Object element) {
//									String laber = (String) element;
//									return laber;
//								}
//							}, res);
//
//					if (dialog.open() == Window.OK) {
//						String ddd = (String) dialog.getFirstResult();
//						pathText.setText(ddd);
//					}
//				}
				String  suffixes [] = {"action","jsp"};
				TowComponentSearchInProjectDialog searchDialog = new TowComponentSearchInProjectDialog(
						shell,suffixes,project);	
				
				if (searchDialog.open() == Window.OK) {
					SearchResult result = (SearchResult)searchDialog.getFirstResult();
					
					
					if ((result.getFile() + "").endsWith(".jar")) {
						Node RootNode = result.getDocument().getDocumentElement();
						Node InformatonNode =SaturnW3CUtil.getFirstChildByName(RootNode, "information");
						String key = SaturnW3CUtil.getChildNodeValue(InformatonNode, "key");
						pathText.setText(result.getBundleName() + "::"+ key);
						
					} else {
						String filePath = result.getFile() + "";
						String tempPath = filePath.replace(result.getSrcName() + "", "");
						pathText.setText(tempPath.replace("\\", "/"));
					}
					
				}
			}

		});

		formtoolkit.createLabel(composite1, Messages
				.getString("MenuItemsDetailsPage.showsequence")); //$NON-NLS-1$
		orderText = createonlyreadText(formtoolkit, composite1);
		orderText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				menuItem.setOrder(orderText.getText().trim());
				menuItemModel.changeMenuItemAttribute(menuItem.getId(),
						MenuItemModel.MENUITEM_ATTRIBUTE_ORDER, orderText
								.getText()); //$NON-NLS-1$

			}
		});

		formtoolkit.paintBordersFor(composite1);
		section.setClient(composite1);
		new Label(composite1, SWT.NONE);
	}

	private Section createSection(FormToolkit formtoolkit, Composite composite,
			String s) {
		Section section = formtoolkit.createSection(composite, 384);
		section.setActiveToggleColor(formtoolkit.getHyperlinkGroup()
				.getActiveForeground());
		section.setToggleColor(formtoolkit.getColors().getColor(
				"org.eclipse.ui.forms.SEPARATOR")); //$NON-NLS-1$
		section.marginHeight = 5;
		section.marginWidth = 5;
		section.setText(s);
		secPart = new SectionPart(section, formtoolkit, SWT.NONE);
		// final Section section_1 = secPart.getSection();
		secPart.initialize(managedform);
		managedform.addPart(secPart);
		TableWrapData tablewrapdata = new TableWrapData(128, 16);
		tablewrapdata.grabHorizontal = true;
		section.setLayoutData(tablewrapdata);
		return section;
	}

	public void commit(boolean onSave) {
		if (setFormInput(menuItem)) {
			refresh();
		}
	}

	public void dispose() {
	}

	public void initialize(IManagedForm managedform) {
		this.managedform = managedform;
	}

	public boolean isDirty() {
		return false;
	}

	public boolean isStale() {
		return false;
	}

	public void refresh() {
		managedform.refresh();
	}

	public void setFocus() {
	}

	public boolean setFormInput(Object input) {
		return true;
	}

	public void selectionChanged(IFormPart part, ISelection selection) {
		IStructuredSelection istructuredselection = (IStructuredSelection) selection;
		if (istructuredselection.size() >= 1) {
			menuItem = (MenuItem) istructuredselection.getFirstElement();

			pathText.setText(menuItem.getPath());
			orderText.setText(menuItem.getOrder());
			labelText.setText(menuItem.getLabel());
		} else {
			pathText.setText(""); //$NON-NLS-1$
			orderText.setText(""); //$NON-NLS-1$
			labelText.setText(""); //$NON-NLS-1$
		}
	}

	private List<String> formatPath(List<String> oldList) {
		List<String> newList = new ArrayList<String>();
		for (int i = 0; i < oldList.size(); i++) {
			String str = oldList.get(i);
			str = str.substring(str.indexOf(project.getName()));
			String[] aaa = str.split("\\\\"); //$NON-NLS-1$
			str = "/" + str.substring(str.indexOf(aaa[2])).replace("\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			newList.add(str);
		}
		return newList;
	}

	private String[] formatArray(String[] array, String extendName) {
		String[] newArray = new String[array.length];
		for (int i = 0; i < array.length; i++) {
			String str = array[i];
			String extend = str.substring(str.lastIndexOf(".") + 1); //$NON-NLS-1$
			if (extendName.equals(extend)) {
				newArray[i] = str;
			}
		}
		return newArray;
	}
}
